﻿using System;
using System.Text;
using System.Runtime.InteropServices;

namespace ProcessConfig
{
    /// <summary>
    /// Đối tượng dùng để xử lý file confing (*.ini).
    /// </summary>
    public class Config
    {
        private string _path = "";
        //dung lenh da co trong kernel32 cua windows
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filepath);

        /// <summary>
        /// Tạo mới 1 đối tượng <see cref="Config" />.
        /// </summary>
        /// <param name="thePath">Đường dẫn.</param>
        public Config(string thePath)
        {
            this._path = thePath;
        }

        /// <summary>
        /// Đọc giá trị.
        /// </summary>
        /// <param name="section">Tiêu đề.</param>
        /// <param name="key">Từ khóa.</param>
        /// <returns></returns>
        public string ReadValue(string section, string key)
        {
            StringBuilder tmp = new StringBuilder(255);
            long i = GetPrivateProfileString(section, key, "", tmp, 255, this._path);
            return tmp.ToString();
        }

        /// <summary>
        /// Ghi giá trị.
        /// </summary>
        /// <param name="section">Tiêu đề.</param>
        /// <param name="key">Từ khóa.</param>
        /// <param name="values">Nội dung.</param>
        public void WriteValue(string section, string key, string values)
        {
            WritePrivateProfileString(section, key, values, this._path);
        }
    }
}
